<template>
  <div>
    <el-breadcrumb separator-class="el-icon-arrow-right">
      <el-breadcrumb-item :to="{ path: '/home' }">首页</el-breadcrumb-item>
      <el-breadcrumb-item>权限管理</el-breadcrumb-item>
      <el-breadcrumb-item>角色列表</el-breadcrumb-item>
    </el-breadcrumb>
    <el-card>
      <!-- 添加角色按钮 -->
      <el-row>
        <el-col>
          <el-button type="primary">添加角色</el-button>
        </el-col>
      </el-row>
      <!-- 角色列表 -->
      <el-table :data="roleList" style="width: 100%" border stripe>
        <!-- 展开列 -->
        <el-table-column type="expand">
          <template slot-scope="scope">
            <!-- 渲染一级权限 -->
            <el-row
              :class="['bgbottom', i == 0 ? 'bgtop':'', 'aligncenter']"
              v-for="(item,i) in scope.row.children"
              :key="item.id"
            >
              <el-col :span="5">
                <el-tag closable @close="threeLevel(scope.row, item.id)">{{item.authName}}</el-tag>
                <i class="el-icon-caret-right"></i>
              </el-col>
              <el-col :span="19">
                <!-- 通过for循环渲染二级权限 -->
                <el-row v-for="(item,i) in item.children" :key="item.id" :class="['aligncenter']">
                  <el-col :span="5">
                    <el-tag
                      type="success"
                      closable
                      @close="threeLevel(scope.row, item.id)"
                    >{{item.authName}}</el-tag>
                    <i class="el-icon-caret-right"></i>
                  </el-col>
                  <el-col :span="14">
                    <el-tag
                      closable
                      @close="threeLevel(scope.row, item.id)"
                      v-for="(item,i) in item.children"
                      :key="item.id"
                      type="warning"
                    >{{item.authName}}</el-tag>
                  </el-col>
                </el-row>
              </el-col>
            </el-row>
          </template>
        </el-table-column>
        <!-- 索引 -->
        <el-table-column type="index" label="#"></el-table-column>
        <el-table-column prop="roleName" label="主管"></el-table-column>
        <el-table-column prop="roleDesc" label="角色描述"></el-table-column>
        <el-table-column label="操作">
          <template slot-scope="scope">
            <el-button size="mini" type="primary" icon="el-icon-edit">编辑</el-button>
            <el-button size="mini" type="danger" icon="el-icon-delete">删除</el-button>
            <el-button size="mini" type="warning" @click="fenpeiDialog(scope.row)" icon="el-icon-setting">分配权限</el-button>
          </template>
        </el-table-column>
      </el-table>
    </el-card>
    <el-dialog title="提示" @close="closeDialog" :visible.sync="fenpeidialogVisible" width="30%">
      <el-tree :data="rightList" :props="treeProps" ref="treeRef" :default-checked-keys="defaultkey" show-checkbox node-key="id" :default-expand-all=true></el-tree>
      <span slot="footer" class="dialog-footer">
        <el-button @click="fenpeidialogVisible = false">取 消</el-button>
        <el-button type="primary" @click="allotRights()">确 定</el-button>
      </span>
    </el-dialog>
  </div>
</template>

<script>
export default {
  data() {
    return {
      roleList: [],
      fenpeidialogVisible:false,
      rightList:[],
      treeProps: {
        children: 'children',
        label: 'authName'
      },
      defaultkey:[116],
      // 等着函数赋值fenpeiDialog
      roleId:'',
    }
  },
  created() {
    this.getRoleList()
  },
  methods: {
    async getRoleList() {
      const { data: res } = await this.$http.get('roles')
      if (res.meta.status !== 200) {
        return this.$message.error(res.meta.msg)
      }
      this.roleList = res.data
    },
    async threeLevel(role, rightId) {
      const res = await this.$confirm('此操作将永久删除, 是否继续?', '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }).catch(err => err)
      if (res !== 'confirm') {
        return this.$message('已取消')
      }
      // console.log(role.children);

      const { data: res2 } = await this.$http.delete(
        `roles/${role.id}/rights/${rightId}`
      )
      if (res2.meta.status !== 200) {
        return this.$message.error(res2.meta.msg)
      }
      // this.getRoleList()
      // 这样不会造成全面刷新
      role.children = res2.data
      // console.log(res2.data);

      this.$message.success('删除成功')
    },
    async fenpeiDialog(role){
      // 存储id，供角色授权使用allotRights
      this.roleId = role.id
      // 获取全部的角色权限
      const {data:res} = await this.$http.get('rights/tree')
      if(res.meta.status !== 200){
        return this.$message.error(res.meta.msg)
      }
      this.rightList = res.data
      // console.log(role);
      var arr = []
      this.digui(role, this.defaultkey)
      console.log(this.defaultkey);
      this.fenpeidialogVisible = true
    },
    digui(role, arr){
      if(!role.children){
        return arr.push(role.id)
      }
      role.children.forEach(element=>{
        // 妈的我呕了，这里居然要加this
        this.digui(element,arr)
      })
    },
    closeDialog(){
      this.defaultkey = []
    },
    // 分配权限确认按钮
    async allotRights(){
      const keys = [
        ...this.$refs.treeRef.getCheckedKeys(),
        ...this.$refs.treeRef.getHalfCheckedKeys()
      ]
      // 将key拼接成新的以逗号分隔的字符串
      const idStr = keys.join(',')
      // console.log(idStr);
      const data = await this.$http.post(`roles/${this.roleId}/rights`,{rids:idStr})
      console.log(data);
      if(data.status!== 200){
        this.$message.error('角色授权失败')
      }
      this.getRoleList()
      this.$message.success('角色授权成功')
      this.fenpeidialogVisible = false
    }
  }
}
</script>

<style lang="less" scoped>
.el-tag {
  margin: 7px;
}
.bgtop {
  border-top: 1px solid #eee;
}
.bgbottom {
  border-bottom: 1px solid #eee;
}
.aligncenter {
  display: flex;
  align-items: center;
}
</style>